package com.lianchuang.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.lianchuang.entity.autoReply.MessageResponse;
import com.lianchuang.service.CoreService;
import com.lianchuang.service.MenuClickService;
import com.lianchuang.util.MessageUtil;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.util.PubFun;
import com.pur.zsms.foodmanage.food.dao.IFoodDao;
import com.pur.zsms.pmsnmanage.user.dao.IWeiXinDao;
import com.pur.zsms.pmsnmanage.user.po.UnitCommentPo;
import com.pur.zsms.pmsnmanage.user.po.UnitMenuPo;
import com.pur.zsms.pmsnmanage.user.po.UnitPo;
import com.pur.zsms.unit.dao.IUnitDao;
import com.weixin.robot.FormatXmlProcess;
import com.weixin.robot.TulingApiProcess;

@Service("coreService")
public class CoreServiceImpl implements CoreService {

	static Logger logger = LoggerFactory.getLogger(CoreServiceImpl.class);

	@Resource(name = "weiXinDao")
	private IWeiXinDao weiXinDao;

	public IWeiXinDao getWeiXinDao() {
		return weiXinDao;
	}

	public void setWeiXinDao(IWeiXinDao weiXinDao) {
		this.weiXinDao = weiXinDao;
	}

	@Resource(name = "unitDao")
	private IUnitDao unitDaoImpl;

	public IUnitDao getUnitDaoImpl() {
		return unitDaoImpl;
	}

	public void setUnitDaoImpl(IUnitDao unitDaoImpl) {
		this.unitDaoImpl = unitDaoImpl;
	}

	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) throws GenericException {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";

			// xml请求解析
			// 调用消息工具类MessageUtil解析微信发来的xml格式的消息，解析的结果放在HashMap里；
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// 从HashMap中取出消息中的字段；
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息内容
			String content = requestMap.get("Content");
			// 从HashMap中取出消息中的字段；

			// logger.info("fromUserName is:" +fromUserName+" toUserName is:"
			// +toUserName+" msgType is:" +msgType);
			// logger.info("content is:" +content);

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				// 微信聊天机器人测试 2015-3-31
				if (content != null) {
					// respContent = TulingApiProcess.getTulingResult(content);
					String message = judge(fromUserName, msgType, content);
					// weiXinDao.addUnitComment(c);

					respContent = message;
					if (respContent == "" || null == respContent) {
						MessageResponse.getTextMessage(fromUserName, toUserName, "服务号暂时无法回复，请稍后再试！");
					}

					logger.info("xml------------------"
					        + MessageResponse.getTextMessage(fromUserName, toUserName, respContent));
					// return FormatXmlProcess.formatXmlAnswer(toUserName,
					// fromUserName, respContent);
					return MessageResponse.getTextMessage(fromUserName, toUserName, respContent);
				}
				// else if (content.startsWith("ZY")) {//查作业
				// String keyWord = content.replaceAll("^ZY" , "").trim();
				// if ("".equals(keyWord)) {
				// respContent = AutoReply.getXxtUsage("24");
				// } else {
				// return XxtService.getHomework("24" , fromUserName ,
				// toUserName , keyWord);
				// }
				// } else if (content.startsWith("SJX")) {//收件箱
				// String keyWord = content.replaceAll("^SJX" , "").trim();
				// if ("".equals(keyWord)) {
				// respContent = AutoReply.getXxtUsage("25");
				// } else {
				// return XxtService.getRecvBox("25" , fromUserName , toUserName
				// , keyWord);
				// }
				// }
				// return MessageResponse.getTextMessage(fromUserName ,
				// toUserName , respContent);
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 事件推送
				String eventType = requestMap.get("Event");// 事件类型

				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {// 订阅
					respContent = "欢迎关注得利库克，我们将遵从“民以食为天，我以客为天”的经营理念，为实现100%顾客满意而努力！";
					return MessageResponse.getTextMessage(fromUserName, toUserName, respContent);
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {// 自定义菜单点击事件
					String eventKey = requestMap.get("EventKey");// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					logger.info("eventKey is:" + eventKey);
					return MenuClickService.getClickResponse(eventKey, fromUserName, toUserName);
				}
			}

			// 开启微信声音识别测试 2015-3-30
			else if (msgType.equals("voice")) {
				String recvMessage = requestMap.get("Recognition");
				// respContent = "收到的语音解析结果："+recvMessage;
				if (recvMessage != null) {
					respContent = TulingApiProcess.getTulingResult(recvMessage);
				} else {
					respContent = "您说的太模糊了，能不能重新说下呢？";
				}
				return MessageResponse.getTextMessage(fromUserName, toUserName, respContent);
			}
			// 拍照功能
			else if (msgType.equals("pic_sysphoto")) {

			} else {
				return MessageResponse.getTextMessage(fromUserName, toUserName, "返回为空");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}

	public String judge(String fromUserName, String msgType, String content) throws GenericException {

		if (content.equals("ALL")) {
			// String msg =
			// "  功能1：查询机构代码 输入‘ALLUN’查看所有中山美食林提供服务单位机构id\r\n  功能2：查询今日菜单 输入‘MENU’+所属单位机构id，查阅今日菜单\r\n  功能3：评论功能  输入‘PL’ + 机构id + ‘1’（好评）或‘2’（中评）或‘3’（差评）+评论 ";
			String msg = "  功能1：查询今日菜单 输入‘MENU’+所属单位机构id，查阅今日菜单\r\n  功能2：评论功能  输入‘PL’ + 机构id + ‘1’（好评）或‘2’（中评）或‘3’（差评）+评论 ";

			return msg;
		}

		/*
		 * if (content.equals("ALLUN")) {
		 * 
		 * List<UnitPo> list = weiXinDao.getAllUnitPo(); StringBuffer msgId =
		 * new StringBuffer(); for (UnitPo unitPo : list) { msgId.append("★" +
		 * unitPo.getUnitName() + ":" + unitPo.getUnitId() + "\r\n"); } return
		 * msgId.toString(); }
		 */

		if (content.length() > 4) {
			String menu = content.substring(0, 4);
			if (menu.equals("MENU")) {
				String unitCode = content.substring(4);
				List<UnitMenuPo> list = weiXinDao.getAllUnitMenuPo(unitCode);
				StringBuffer msgId = new StringBuffer();
				if (list != null && list.size() > 0) {
					msgId.append(list.get(0).getMenuText());
				} else {
					msgId.append("今日菜单还没有录入");
				}
				return msgId.toString();
			}

			String sign = content.substring(0, 2);
			if (sign.equals("PL")) {
				String unitCode = content.substring(2, 6);
				String commentState = content.substring(6, 7);
				String text = content.substring(7);
				if (!commentState.equals("1") && !commentState.equals("2") && !commentState.equals("3")) {
					return "如用今日菜品评论功能请输入‘PL’字母 + 机构id + 数字‘1’或‘2’或‘3’再加上你的评论。（1代表好评，2代表中评，3代表差评）";
				} else {
					int unitId = unitDaoImpl.getUnitIdByUnitCode(unitCode);
					if (unitId == 0) {
						return "您输入的机构代码不存在，  请按照格式输入‘PL’字母 + 机构id + 数字‘1’或‘2’或‘3’再加上你的评论。（1代表好评，2代表中评，3代表差评）";
					}
					UnitCommentPo tPo = new UnitCommentPo();
					tPo.setUnitId(Integer.valueOf(unitId));
					tPo.setCommentDate(PubFun.getCurrentDate());
					tPo.setCommentState(Integer.valueOf(commentState));
					tPo.setCommentText(text);
					tPo.setFromUserName(fromUserName);
					try {
						weiXinDao.addUnitComment(tPo);
					} catch (GenericException e) {
						logger.info("异常----------" + e.toString());
						return "插入异常";
					}
				}
			} else {
				return "请输入'ALL' 来查询所有功能。";
			}

		} else {
			return "请输入'ALL' 来查询所有功能。";
		}

		return "操作成功，谢谢您的使用。";
	}
}
